package com.killer_jin.core.common.interceptor;

import com.killer_jin.core.common.util.auth.TokenAuthenticater;
import com.killer_jin.core.common.util.api.ApiUserHolder;
import com.killer_jin.core.module.system.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jiayu
 * @since 2019/07/11
 */

@Component
public class UserApiInterceptor implements HandlerInterceptor {
    @Autowired
    private ApiUserHolder userHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        userHolder.setUser(null);
        userHolder.setErrorMsg(null);
        Authentication authentication = null;

        try {
            authentication = TokenAuthenticater.getCommonAuthentication(request);
        } catch (RuntimeException e) {
            userHolder.setErrorMsg(e.getMessage());
        }

        if (authentication != null) {
            //verify web token
            String userId = String.valueOf(authentication.getPrincipal());
            // 根据token获取用户id并且查询数据库获取用户信息 Todo
            /*User user = userDao.selectByPrimaryKey(userId);

            if (user == null || user.getDeletedTime() != null) {
                userHolder.setErrorMsg("user not exist");
            } else {
                ApiUser apiUser = new ApiUser();
                apiUser.setUserId(user.getId());
                apiUser.setUserName(user.getNickname());

                userHolder.setUser(apiUser);
            }*/
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
    }
}
